package com.wuyangnju.lj.simulation.master.servlet;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;

import com.wuyangnju.lj.simulation.common.Plan;
import com.wuyangnju.lj.simulation.master.service.ComputionService;

@SuppressWarnings("serial")
public class ComputionInitAndStartServlet extends HttpServlet {
	private static final Log log = LogFactory
			.getLog(ComputionInitAndStartServlet.class);
	private static final ObjectMapper mapper = new ObjectMapper();

	private ComputionService computionService;
	{
		computionService = ComputionService.get();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/plain");

		List<Plan> plans = null;
		double alpha = 0, theta = 0, k = 0;

		try {

			int from1 = Integer.parseInt(req.getParameter("from1"));
			int to1 = Integer.parseInt(req.getParameter("to1"));
			int from2 = Integer.parseInt(req.getParameter("from2"));
			int to2 = Integer.parseInt(req.getParameter("to2"));
			plans = new LinkedList<Plan>();

			for (int x1 = 1; x1 <= 18; x1++) {
				for (int x2 = 1; x2 <= 19 - x1; x2++) {
					for (int x3 = 1; x3 <= 20 - x1 - x2; x3++) {
						for (int x4 = 1; x4 <= 19; x4++) {
							int x5 = 20 - x4;
							plans.add(new Plan(x1, x2, x3, x4, x5));
						}
					}
				}
			}
			// for (int i = from1; i <= to1; i++) {
			// for (int j = from2; j <= to2; j++) {
			// if (i <= j) {
			// plans.add(new Plan(i, j));
			// }
			// }
			// }

			alpha = Double.parseDouble(req.getParameter("alpha"));
			theta = Double.parseDouble(req.getParameter("theta"));
			k = plans.size();

			log.info(" from1: " + from1 + " to1: " + to1 + " from2: " + from2
					+ " to2: " + to2 + " alpha: " + alpha + " theta: " + theta
					+ " k: " + k);

			computionService.initAndStart(plans, alpha, theta, k);

			resp.getWriter().println(
					" plans: " + mapper.writeValueAsString(plans) + " alpha: "
							+ alpha + " theta: " + theta + " k: " + k);
			log.info(" plans: " + mapper.writeValueAsString(plans) + " alpha: "
					+ alpha + " theta: " + theta + " k: " + k);

		} catch (Exception e) {

			log.error("compution init or start error.", e);
			resp.getWriter().println(
					"compution init or start error. " + e.getMessage());

		}
	}
}
